package com.mouse.fast_sql.service;

import com.mouse.fast_sql.constant.Config;
import com.mouse.fast_sql.util.FileUtil;
import com.mouse.fast_sql.util.StringUtil;
import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class InitServiceImpl implements InitService {
    private static final String baseTempPath = "src/main/java/com/mouse/fast_sql/temp";

    public void init(IntrospectedTable introspectedTable) {
        createService(introspectedTable);
        createServiceImpl(introspectedTable);

        createSearchParam(introspectedTable);
        createAddEditParam(introspectedTable);
        createVo(introspectedTable);

        createFeight(introspectedTable);
        createFallback(introspectedTable);
        createController(introspectedTable);

        createInsertSql(introspectedTable);
    }

    private void createInsertSql(IntrospectedTable introspectedTable) {
        String excelType = "1";
        StringBuffer sb = new StringBuffer("insert into istore_finance_config(field_name,name,sort,type,excel_type) values ");
        List<IntrospectedColumn> baseColumns = introspectedTable.getBaseColumns();
        int sort = 1;
        for (IntrospectedColumn column : baseColumns) {
            String javaProperty = column.getJavaProperty();
            String remarks = column.getRemarks();
            try {
                String fullyQualifiedName = column.getFullyQualifiedJavaType().getFullyQualifiedName();
                if (fullyQualifiedName.contains("Double")) {
                    sb.append("\n('" + javaProperty + "'");
                    sb.append(",'" + remarks + "'");
                    sb.append("," + sort);
                    sb.append(",'1'");
                    sb.append(",'" + excelType + "'");
                    sb.append("),");
                    sort++;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String string = sb.toString();
        if (string.endsWith(",")) {
            string=string.substring(0,string.length()-1)+";";
        }
//        System.out.println(string);
    }

    private void createFallback(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
//        System.out.println(introspectedTable.getFullyQualifiedTableNameAtRuntime()+"->"+Entity);
        String apiTags = entity;
        Config.TableConfig tableConfig = Config.getTableConfig(Entity);
//        if (tableConfig != null) apiTags = tableConfig.desc + "接口(" + tableConfig.author + ")";
        if (tableConfig != null) apiTags = tableConfig.desc + "接口";
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/fallback.temp";//模版路径
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@apiTags", apiTags)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@desc", tableConfig.desc)
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/feign/fallback/" + Entity + "FeignFallback.java", newContent);
    }

    private void createFeight(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
//        System.out.println(introspectedTable.getFullyQualifiedTableNameAtRuntime()+"->"+Entity);
        String apiTags = entity;
        Config.TableConfig tableConfig = Config.getTableConfig(Entity);
        if (tableConfig != null) apiTags = tableConfig.desc + "接口(" + tableConfig.author + ")";
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/feign.temp";//模版路径
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@apiTags", apiTags)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@desc", tableConfig.desc)
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/feign/" + Entity + "Feign.java", newContent);
    }

    private void createController(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
//        System.out.println(introspectedTable.getFullyQualifiedTableNameAtRuntime()+"->"+Entity);
        String apiTags = entity;
        Config.TableConfig tableConfig = Config.getTableConfig(Entity);
        if (tableConfig != null) apiTags = tableConfig.desc + "接口";
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/controller.temp";//模版路径
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@apiTags", apiTags)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@desc", tableConfig.desc)
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/rest/" + Entity + "Controller.java", newContent);
    }

    private void createAddEditParam(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/addEditParam.temp";//模版路径

        StringBuffer keySb = new StringBuffer();
        StringBuffer importPackageSb = new StringBuffer();
        Set<String> importPackageSet = new HashSet<String>();
        List<IntrospectedColumn> columns = new ArrayList<IntrospectedColumn>();
        columns.addAll(introspectedTable.getPrimaryKeyColumns());
        columns.addAll(introspectedTable.getBaseColumns());
        for (IntrospectedColumn column : columns) {
            if (Config.commonParam.contains(column.getJavaProperty())) continue;
            FullyQualifiedJavaType type = column.getFullyQualifiedJavaType();
            keySb.append("\n");
            if ("String".equals(type.getShortName())) {
                importPackageSet.add("import javax.validation.constraints.NotBlank;\n");
                importPackageSet.add("import org.hibernate.validator.constraints.Length;\n");
                keySb.append("\t@NotBlank(message = \"" + column.getRemarks() + "不能为空|" + column.getActualColumnName().replaceAll("_", " ") + " is not blank\")\n");
                keySb.append("\t@Length(min = 1, max = " + column.getLength() + ", message = \"" + column.getRemarks() + "长度大于1小于" +
                        column.getLength() + "|" + column.getActualColumnName().replaceAll("_", " ") +
                        " length greater than 1 and less than " + column.getLength() + "\")\n");
            } else {
                importPackageSet.add("import javax.validation.constraints.NotNull;\n");
                List<IntrospectedColumn> primaryKeyColumns = introspectedTable.getPrimaryKeyColumns();
                boolean nullFlag = true;
                for (IntrospectedColumn introspectedColumn : introspectedTable.getPrimaryKeyColumns()) {
                    if (introspectedColumn.getJavaProperty().equals(column.getJavaProperty())) {
                        nullFlag = false;
                        break;
                    }
                }
                if (nullFlag)
                    keySb.append("\t@NotNull(message = \"" + column.getRemarks() + "不能为空|" + column.getActualColumnName().replaceAll("_", " ") + " is not null\")\n");

            }
            keySb.append("\t@ApiModelProperty(\"" + column.getRemarks() + "\")\n");
            keySb.append("\tprivate " + type.getShortName() + " " + column.getJavaProperty() + ";\n");
            String fullyQualifiedName = type.getFullyQualifiedName();
            if (!fullyQualifiedName.startsWith("java.lang"))
                importPackageSet.add("import " + type.getFullyQualifiedName() + ";\n");

        }
        for (String importPackage : importPackageSet) importPackageSb.append(importPackage);
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@data", keySb.toString())
                .replaceAll("@importPackage", importPackageSb.toString())
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/entity/param/" + Entity + "Param.java", newContent);
    }

    private void createReqParam(IntrospectedTable introspectedTable) {
        //add
    }


    private void createVo(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/vo.temp";//模版路径

        StringBuffer keySb = new StringBuffer();
        StringBuffer importPackageSb = new StringBuffer();
        Set<String> importPackageSet = new HashSet<String>();
        List<IntrospectedColumn> columns = new ArrayList<IntrospectedColumn>();
        columns.addAll(introspectedTable.getPrimaryKeyColumns());
        columns.addAll(introspectedTable.getBaseColumns());
        for (IntrospectedColumn column : columns) {
            if (Config.commonParam.contains(column.getJavaProperty())) continue;
            FullyQualifiedJavaType type = column.getFullyQualifiedJavaType();
            keySb.append("\n");
//            if("String".equals(type.getShortName())){
//                importPackageSet.add("import javax.validation.constraints.NotBlank;\n");
//                keySb.append("\t@NotBlank(\"" + column.getRemarks() + "不能为空|"+column.getActualColumnName().replaceAll("_"," ") +" is not blank\")\n");
//            }else {
//                importPackageSet.add("import javax.validation.constraints.NotNull;\n");
//                keySb.append("\t@NotNull(\"" + column.getRemarks() + "不能为空|"+column.getActualColumnName().replaceAll("_"," ") +" is not null\")\n");
//            }
            keySb.append("\t@ApiModelProperty(\"" + column.getRemarks() + "\")\n");
            keySb.append("\tprivate " + type.getShortName() + " " + column.getJavaProperty() + ";\n");
            String fullyQualifiedName = type.getFullyQualifiedName();
            if (!fullyQualifiedName.startsWith("java.lang"))
                importPackageSet.add("import " + type.getFullyQualifiedName() + ";\n");

        }
        for (String importPackage : importPackageSet) importPackageSb.append(importPackage);
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@data", keySb.toString())
                .replaceAll("@importPackage", importPackageSb.toString())
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/entity/vo/" + Entity + "Vo.java", newContent);
    }

    private void createSearchParam(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/param.temp";//模版路径

        StringBuffer keySb = new StringBuffer();
        StringBuffer importPackageSb = new StringBuffer();
        Set<String> importPackageSet = new HashSet<String>();
        List<IntrospectedColumn> columns = new ArrayList<IntrospectedColumn>();
        columns.addAll(introspectedTable.getPrimaryKeyColumns());
        columns.addAll(introspectedTable.getBaseColumns());
        for (IntrospectedColumn column : columns) {
            if (Config.commonParam.contains(column.getJavaProperty())) continue;
            FullyQualifiedJavaType type = column.getFullyQualifiedJavaType();
            keySb.append("\n");
            keySb.append("\t@ApiModelProperty(\"" + column.getRemarks() + "\")\n");
            keySb.append("\tprivate " + type.getShortName() + " " + column.getJavaProperty() + ";\n");
            String fullyQualifiedName = type.getFullyQualifiedName();
            if (!fullyQualifiedName.startsWith("java.lang"))
                importPackageSet.add("import " + type.getFullyQualifiedName() + ";\n");

        }
        for (String importPackage : importPackageSet) importPackageSb.append(importPackage);
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@data", keySb.toString())
                .replaceAll("@importPackage", importPackageSb.toString())
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/entity/param/" + Entity + "SearchParam.java", newContent);
    }

    private void createServiceImpl(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/serviceImpl.temp";//模版路径
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/service/impl/" + Entity + "ServiceImpl.java", newContent);

    }

    private void createService(IntrospectedTable introspectedTable) {
        String Entity = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType()).getShortName();
        String entity = StringUtil.lowerFirstWord(Entity);
        String basePackageName = Config.modelPackage;
        String tempPath = baseTempPath + "/service.temp";//模版路径
        String newContent = FileUtil.readFile(tempPath)
                .replaceAll("@basePackage", basePackageName)
                .replaceAll("@Entity", Entity)
                .replaceAll("@entity", entity);
        FileUtil.writeFile(FileUtil.getCodePath() + "/service/" + Entity + "Service.java", newContent);
    }

}
